import { ref } from 'vue'
import { defineStore } from 'pinia'
import Taro from '@tarojs/taro'
import http from '@/utils/http'

export const useUserStore = defineStore('user', () => {
  // 定义状态
  const token = ref(Taro.getStorageSync('token') || '')
  const info = ref({
    id: 0,
    avatar: "",
    nickname: "",
    referee: '',
    telephone: '',
    isworker: false
  })

  // 定义登录方法
  const doLogin = async () => {
    const loginRes = await Taro.login()
    console.log('loginRes', loginRes)

    if (loginRes.code) {
      try {
        const res:any = await http.post('/index.php/index/api/index', {
          Func: 'regOrLogin',
          data: { code: loginRes.code }
        })
        
        console.log('res', res)
        if (res.error === 0) {
          token.value = res.data
          Taro.setStorageSync('token', res.data)
          doGetInfo()
        }
      } catch (error) {
        console.error('登录请求失败', error)
      }
    }
  }

  // 定义获取用户信息方法
  const doGetInfo = async () => {
    try {
      const res:any = await http.post('/index.php/index/api/index', {
        Func: 'getUserInfo',
        data: {}
      })
      
      console.log('res', res)
      if (res.error === 0) {
        info.value = res.data || { }
      }
    } catch (error) {
      console.error('获取用户信息失败', error)
    }
  }

  const doUpdateInfo = async (data: any) => {
    try {
      const res:any = await http.post('/index.php/index/api/index', {
        Func: 'editUserInfo',
        data: {
          nickname: data.nickname,
          avatar: data.avatar,
          telephone: info.value.telephone,
        }
      })

      console.log('res', res)
      if (res.error === 0) {
        doGetInfo()
      }
    } catch (error) {
      console.error('更新用户信息失败', error)
    }
  }

  return {
    token,
    info,
    doLogin,
    doGetInfo,
    doUpdateInfo
  }
})